﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileHelpers;
using EntityAndDomainLibrary.EntityModel;
using EntityAndDomainLibrary.DomainModel;
using Log4NetLibrary;
using System.Threading;

namespace MeterService.Helpers
{
    public static class ReadWriteHelper
    {
        static DataBaseAccess dbacess = new DataBaseAccess();
        static ILogService logService;
        
        public static IList<EM_TOUData> ReadAndWriteToDB(string filename,FileArchive archive)
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();
                logService = new FileLogService(typeof(ReadWriteHelper));

                FileHelperEngine engine = new FileHelperEngine(typeof(EM_TOUData));
                EM_TOUData[] res = engine.ReadFile(filename)as EM_TOUData[];

                IList<EM_TOUData> _listmeterdata = res.ToList<EM_TOUData>();
                
                foreach (EM_TOUData meterdata in _listmeterdata)
                {
                  
                    dbacess.SaveTOUDatas(Mapper.MapEM_TOUDataToTOUData(meterdata, archive));
                }

                string[] file = filename.Split('\\');
                new Thread(() =>
                    {
                        WriteDataToOutputFile(file[file.Count()-1], _listmeterdata);
                    }
                ).Start();

                return res.ToList<EM_TOUData>();
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
                return null;
            }
        }

        public static void WriteDataToOutputFile(string filename,IList<EM_TOUData> _listdata)
        {
            try
            {
               
                IList<Output> _listoutput = Mapper.ConvertDomainMeterDataToOuputData(_listdata);
                FileHelperEngine engine = new FileHelperEngine(typeof(Output));

                engine.WriteFile(dbacess.GetSystemSettings().OutputFileLocation+"/"+filename,_listoutput);
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
                //return null;
            }
        }

    }
}
